﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.IO;
using System.Web.Security;
using System.Security.Cryptography;

namespace TaiLieu
{
    public class ConvertType
    {
      

        /// <summary>
        ///Function covertt string type bool become int
        /// </summary>
        /// <param name="?"> true to 1</param>
        public static int ConverStringToInt(string str)
        {
            if (str == "true" || str == "True")
                return 1;
            else
                if (str == "false" || str == "False")
                    return 0;
            return -1;
        }
     
        public static string ToStringMoney(object obj)
        {
            string temp = "";
            temp = ToInt(obj).ToString("N");
            temp = temp.Substring(0, temp.LastIndexOf("."));
            temp = temp.Replace(",", ".");
            return temp;
        }
        public static bool ConverStringToBool(string str)
        {
            return ConverIntToBool(ConverStringToInt(str));
        }
        public static bool TestString(string str)
        {
            if ((str == "true" || str == "True") || (str == "false" || str == "False"))
                return true;
            return false;
        }
        public static int ConverStringToInt1(string str)
        {
            if (str == "male" || str == "Male")
                return 1;
            else
                if (str == "Female" || str == "female")
                    return 0;
            return -1;
        }
      
        /// <summary>
        /// function convert int to bool 
        /// </summary>
        /// <param name="number">number 0 or 1</param>
        /// <returns>true if number=1 </returns>
        public static bool ConverIntToBool(int number)
        {
            if (number == 1)
                return true;
            return false;
        }
        /// <summary>
        /// function convert bool to int 
        /// </summary>
        /// <param name="number">bol is true or false</param>
        /// <returns>1 if bol=true .. </returns>
        public static string ConverIntToString(int number)
        {
            if (number == 1)
                return "true";
            return "false";
        }

        public static string ConvertTrueFalse(string bol)
        {
            string _bool = bol.Trim().ToLower();
            if (_bool == "true")
                return "false";
            else
                if (_bool == "false")
                    return "true";
            return "";
        }
        public static string RemoveHtml(string text)
        {
            if (text.IndexOf("<p>") == 0)
            {
                text = text.Remove(0, 3);
            }
            if (text.IndexOf("<p") == 0)
            {
                text = text.Remove(0, 2);
                text = text.Remove(0, text.IndexOf("<"));
            }
            if (text.LastIndexOf("</p>") == text.Length - 4)
            {
                text = text.Substring(0, text.LastIndexOf("</p>"));
            }
            return text;
        }
        public static float ToFloat(object obj)
        {
            try
            {
                float rs = float.Parse(obj.ToString());
                if (rs < 0) return 0;
                return rs;
            }
            catch
            {
                return 0;
            }
        }
        public static string ToString(object obj)
        {
            try
            {
                return Convert.ToString(obj);
            }
            catch
            {
                return "";
            }
        }
        public static string DeleteTagPHeadFirstRowInFCK(object obj)
        {
            try
            {
                string tam = Convert.ToString(obj).Substring(3, Convert.ToString(obj).Length - 3);
                string tam1 = tam.Substring(0, tam.Length -4);
                return tam1;
            }
            catch
            {
                return "";
            }
        }
        public static DateTime ToDateTime(object obj)
        {
            try
            {
                return Convert.ToDateTime(obj);
            }
            catch
            {
                return Convert.ToDateTime("1/1/2009");
            }
        }

        // bac bien dua
        //public static int ToInt(object obj)
        //{
        //    try
        //    {
        //        int x = int.Parse(obj.ToString());
        //        if (x < 0)
        //        {
        //            return 0;
        //        }
        //        return x;
        //    }
        //    catch
        //    {
        //        return 0;
        //    }

        //}
        public static int ToInt(object obj)
        {
            try
            {
                return Convert.ToInt32(obj);
            }
            catch
            {
                return 0;
            }
        }
        
        public static bool ToBool(object obj)
        {
            try
            {
                return Convert.ToBoolean(obj);
            }
            catch
            {
                return false;
            }
        }
        public static string ToSQLString(string str)
        {
            str = str.Trim();
            string s = "";
            for (int i = 0; i < str.Length; i++)
            {
                if ((((str[i] >= 'a') && (str[i] <= 'z')) || ((str[i] >= 'A') && (str[i] <= 'Z'))) || ((str[i] >= '0') && (str[i] <= '9')))
                {
                    s = s + str[i];
                }
            }
            return s;
        }
        public static string ToSafeString(object obj)
        {
            try
            {
                return ToString(obj).Replace("<", "&lt").Replace(">", "&gt").Replace("'", "''").Replace("script", " s c r i p t ").Replace("this", " t h i s ").Trim();
            }
            catch
            {
                return "";
            }
        }


        public static string ConvertHTML(string s)
        {
            s = s.Replace("&lt;", "<");
            s = s.Replace("&gt;", ">");
            s = s.Replace("[br]", "<br>");
            s = s.Replace("[br]", "</br>");
            s = s.Replace("[p]", "<p>");
            s = s.Replace("[/p]", "<p>");
            s = s.Replace("[b]", "<b>");
            s = s.Replace("[/b]", "</b>");
            s = s.Replace("[i]", "<i>");
            s = s.Replace("[/i]", "</i>");
            return s;
        }


        public static string ConvertSafe(string s)
        {
            s = s.Replace("<", "&lt;");
            s = s.Replace(">", "&gt;");
            s = s.Replace('\r', '<');
            s = s.Replace('\n', '>');
            s = s.Replace("<>", "[br]");
            s = s.Replace("&", "&amp;");
            s = s.Replace("'", "&apos;");
            return s;
        }
        public static string ConvertSafeOff(string s)
        {
            s = s.Replace("&lt;","<");
            s = s.Replace("&gt;", ">");
            s = s.Replace('<', '\r');
            s = s.Replace('>', '\n');
            s = s.Replace("[br]", "<>");
            s = s.Replace("&amp;", "&");
            s = s.Replace("&apos;", "'");
            return s;
        }

        public static string ConvertToEdit(string s)
        {
            s = s.Replace("&lt;", "<");
            s = s.Replace("&gt;", ">");
            s = s.Replace("[br]", "[]");
            s = s.Replace('[', '\r');
            s = s.Replace(']', '\n');
            return s;
        }
        public static string ChuyenDoiCoDauSangKhongDau_MatKhoangTrang(string str)
        {
            string str1 = "áàảãạăắằẳẵặâấầẩẫậéèẻẽẹêếềểễệíìỉĩịóòỏõọôốồổỗộơớờởỡợúùủũụưứừửữựýỳỷỹỵđ";
            string str2 = "aaaaaaaaaaaaaaaaaeeeeeeeeeeeiiiiiooooooooooooooooouuuuuuuuuuuyyyyyd";
            string keyWork = "";
            foreach (char cha in str.Trim().ToLower().Replace(" ", ""))
            {
                if (str1.Contains(cha.ToString()) == true)
                {
                    keyWork += str2[str1.LastIndexOf(cha)];
                }
                else
                { keyWork += cha; }
            }
            return keyWork;
        }
        public static string ChuyenDoiCoDauSangKhongDau_ConKhoangTrang(string str)
        {
            string str1 = "áàảãạăắằẳẵặâấầẩẫậéèẻẽẹêếềểễệíìỉĩịóòỏõọôốồổỗộơớờởỡợúùủũụưứừửữựýỳỷỹỵđ";
            string str2 = "aaaaaaaaaaaaaaaaaeeeeeeeeeeeiiiiiooooooooooooooooouuuuuuuuuuuyyyyyd";
            string keyWork = "";
            foreach (char cha in str.Trim().ToLower())
            {
                if (str1.Contains(cha.ToString()) == true)
                {
                    keyWork += str2[str1.LastIndexOf(cha)];
                }
                else
                { keyWork += cha; }
            }
            return keyWork;
        }
        public static string ChuyenDoiCoDauSangKhongDau_ChuyenKhoangTrangSangKiTuKhac(string str,string kiTuThayThe)
        {
            return ChuyenDoiCoDauSangKhongDau_ConKhoangTrang(str.ToLower().Replace("    ", " ").Replace(" - ", " ").Replace("   ", " ").Replace("  ", " ").Replace(" ", kiTuThayThe));
        }
       
        public static DateTime StringToDateTime(object obj)
        {
            try
            {
                return Convert.ToDateTime(obj);
            }
            catch
            {
                return DateTime.MinValue;
            }
        }
        public static DateTime ToDateTime(object obj, string strFormat)
        {
            try
            {
                string dtString = ToString(obj);
                string[] arr = new string[2];
                DateTime dt = DateTime.MinValue;
                if (dtString.IndexOf("/") > -1)
                {
                    arr = dtString.Split(new char[] { '/' });
                }
                else if (dtString.IndexOf("-") > -1)
                {
                    arr = dtString.Split(new char[] { '-' });
                }
                else
                {
                    return dt;
                }
                switch (strFormat)
                {
                    case "dd/mm/yyyy":
                    case "dd-mm-yyyy":
                        dt = ToDateTime(arr[1] + "/" + arr[0] + "/" + arr[2]);
                        break;

                    case "yyyy/mm/dd":
                    case "yyyy-mm-dd":
                        dt = ToDateTime(arr[1] + "/" + arr[2] + "/" + arr[0]);
                        break;

                    case "yyyy/dd/mm":
                    case "yyyy-dd-mm":
                        dt = ToDateTime(arr[2] + "/" + arr[1] + "/" + arr[0]);
                        break;

                    default:
                        dt = ToDateTime(obj);
                        break;
                }
                return dt;
            }
            catch
            {
                return DateTime.MinValue;
            }
        }
        public static string ToDateTimeString(DateTime dt, string strFormat)
        {
            string dateTime;
            string strDay = ToString(dt.Day).PadLeft(2, '0');
            string strMonth = ToString(dt.Month).PadLeft(2, '0');
            string strYear = ToString(dt.Year);
            try
            {
                string tam = strFormat;
                if (tam == null)
                {
                    goto Label3;
                }
                if (!(tam == "dd/mm/yyyy") && !(tam == "dd-mm-yyyy"))
                {
                    if ((tam == "yyyy/mm/dd") || (tam == "yyyy-mm-dd"))
                    {
                        goto Label1;
                    }
                    if (tam == "yyyy/dd/mm")
                    {
                        goto Label2;
                    }
                    goto Label3;
                }
                string dtString = strDay + "/" + strMonth + "/" + strYear;
                goto Label4;
            Label1:
                dtString = strYear + "/" + strMonth + "/" + strDay;
                goto Label4;
            Label2:
                dtString = strYear + "/" + strDay + "/" + strMonth;
                goto Label4;
            Label3:
                dtString = "";
            Label4:
                dateTime = dtString;
            }
            catch
            {
                dateTime = string.Empty;
            }
            return dateTime;
        }
        //public static string EncodePassword(string strPassword, string strFormat)
        //{
        //    //if (strFormat == string.Empty)
        //    //{
        //    //    strFormat = "MD5";
        //    //}
        //    //return FormsAuthentication.HashPasswordForStoringInConfigFile(strPassword, strFormat);
        //}
        public static string EncodePassword(string pass)
        {
            Byte[] original;
            Byte[] encoder;
            MD5 md5 = new MD5CryptoServiceProvider();
            original = ASCIIEncoding.Default.GetBytes(pass);
            encoder = md5.ComputeHash(original);
            return BitConverter.ToString(encoder);
        }
        public static string RandomString(int length, bool LowerString, bool Number)
        {
            Random AppRandom = new Random((int)DateTime.Now.Ticks);
            string str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            if (Number)
            {
                str = str + "0123456789";
            }
            if (LowerString)
            {
                str = str + "abcdefghijklmnopqrstuvwxyz";
            }
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < length; i++)
            {
                int r = AppRandom.Next(0, str.Length);
                sb.Append(str.Substring(r, 1));
            }
            return sb.ToString();
        }
        public static string CheckEmail(string email)
        {
            int a = email.IndexOf('@');
            int dot = email.LastIndexOf('.');
            if (a > 1 && dot - 1 > a)
            {
                return email;
            }
            return string.Empty;
        }
        public static string CatKhoangTrang(string str)
        {
            string result = string.Empty;
            str.Trim();
            for (int i = 0; i < str.Length; i++)
                if (str[i].CompareTo(' ') != 0)
                    result += str[i];
            return result;
        }
        //public static bool KiemTraFile(string fileType)
        //{
        //    //string type = Config.AcceptFileType();
        //    //if (fileType == "")
        //    //    return false;
        //    //if (type.Contains(fileType.ToLower()) == true)
        //    //    return true;
        //    //return false;
        //}

        // ---------------- Ma hoa chuoi ki tu ---------------------
        // Internal value of the phrase used to generate the secret key
        //private string _Phrase = "";
        // Internal initialization vector value to 
        // encrypt/decrypt the first block
        private byte[] _IV;

        // Internal secret key value
        private byte[] _Key;
        enum TransformType
        {
            encrypt = 0,
            decrypt = 1
        }
        /// <summary>
        /// Ma hoa mot chuoi
        /// </summary>
        /// <param name="str"> Dua vao chuoi can ma hoa</param>
        /// <returns>Tra ve mot chuoi da ma hoa</returns>
        public string Encrypt(string str)
        {
            try
            {
                if (str.Length > 0)
                {
                    // Write the encrypted value into memory
                    //Luu ma hoa vao bo nho tam
                    byte[] input = Encoding.UTF8.GetBytes(str);
                    // Retrieve the encrypted value and return it
                    //Khoi phuc ma hoa va tra lai no
                    return (Convert.ToBase64String(Transform(input, TransformType.encrypt)));
                }
                else
                    return null;
            }
            catch
            {
                return null;
            }
        }
        /// <summary>
        /// Giai ma mot chuoi da ma hoa
        /// </summary>
        /// <param name="decryptValue">Dua vao chuoi can giai ma</param>
        /// <returns>Tra ve mot chuoi da duoc giai ma</returns>
        public string Decrypt(string decryptValue)
        {
            try
            {
                if (decryptValue.Length > 0)
                {
                    // Write the encrypted value into memory  
                    byte[] intput = Convert.FromBase64String(decryptValue);
                    // Retrieve the decrypted value and return it
                    return (Encoding.UTF8.GetString(Transform(intput, TransformType.decrypt)));
                }
                else
                    return null;
            }
            catch
            {
                return null;
            }
        }
        private byte[] Transform(byte[] input, TransformType transformType)
        {
            CryptoStream cryptoStream = null;// Stream used to encrypt(Donh duoc dung de ma hoa)
            RijndaelManaged rijndael = null;//Rijndael Provider
            ICryptoTransform rijndTransform = null;//Encrypting object
            MemoryStream memoryStream = null;//Stream contain data
            try
            {
                //Create the crypt to object
                rijndael = new RijndaelManaged();
                rijndael.Key = this._Key;
                rijndael.IV = this._IV;
                if (transformType == TransformType.encrypt)
                    rijndTransform = rijndael.CreateEncryptor();
                else
                    rijndTransform = rijndael.CreateDecryptor();
                if ((input != null) && (input.Length > 0))
                {
                    memoryStream = new MemoryStream();
                    cryptoStream = new CryptoStream(memoryStream, rijndTransform, CryptoStreamMode.Write);
                    cryptoStream.Write(input, 0, input.Length);
                    cryptoStream.FlushFinalBlock();
                    return memoryStream.ToArray();
                }
                return null;
            }
            catch
            {
                return null;
            }
            finally
            {
                if (rijndael != null) rijndael.Clear();
                if (rijndTransform != null) rijndTransform.Dispose();
                if (cryptoStream != null) cryptoStream.Close();
                if (memoryStream != null) memoryStream.Close();
            }

        }
        private void GenerateKey(string SecretPhrase)
        {
            // Initialize internal values
            this._Key = new byte[24];
            this._IV = new byte[16];

            // Perform a hash operation using the phrase.  This will 
            // generate a unique 32 character value to be used as the key.
            byte[] bytePhrase = Encoding.ASCII.GetBytes(SecretPhrase);
            SHA384Managed sha384 = new SHA384Managed();
            sha384.ComputeHash(bytePhrase);
            byte[] result = sha384.Hash;

            // Transfer the first 24 characters of the hashed value to the key
            // and the remaining 8 characters to the intialization vector.
            for (int loop = 0; loop < 24; loop++) this._Key[loop] = result[loop];
            for (int loop = 24; loop < 40; loop++) this._IV[loop - 24] = result[loop];
        }
        
    }
}
